package com.shouhuobao.take.mine;

import android.graphics.Bitmap;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;

import java.util.HashMap;
import java.util.Map;

import droid.frame.ui.utils.Utils;

/**
 * Created by joker on 2017/8/16.
 * 快递员使用二维码
 */
public class ExpressUserQRCodeFragment extends BaseFragment {

    ImageView mUserQRCodeIV;

    @Override
    protected void findViewById() {
        setContentView(R.layout.fragment_take_qr_code);
        super.findViewById();
        mUserQRCodeIV = (ImageView) findViewById(R.id.qr_code_IV);
        UserBean userBean = AppCache.getUser();
        String content = "https://wx.shouhuobao.com/stationId?code=" + userBean.getCode();
        Bitmap bitmap = generateBitmap(content, Utils.dpToPx(75, getResources()), Utils.dpToPx(75, getResources()));
        if (bitmap != null) {
            mUserQRCodeIV.setImageBitmap(bitmap);
        }
    }

    /**
     * 生成二维码
     *
     * @param content
     * @param width
     * @param height
     * @return
     */
    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}
